
package sound;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 *
 * @author Yannick
 */
public class UDPStream extends Thread {

    private static DatagramSocket rs;
    private String ipa;
    //poort inkomende udp
    private int inport;
    //poort uitgaande udp
    private int uitport;
    public static Read r;
    public Write w = new Write();


    /**
     * Client side udpstream
     * lezen en schrijven starten
     * @param hostname = VoIP Server
     * @param port = poort op naar te schrijven op server
     */
    public UDPStream(String hostname, int port) {
        ipa = hostname;
        try {
            rs = new DatagramSocket();
            r = new Read();
            r.start();
            w.start();
            this.uitport = port;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Client-side
     * @return Poort waarop gelezen wordt
     */
    public static int getLocalPort(){
        return rs.getLocalPort();
    }

    public class Write extends Thread {

        public void write(byte[] tempBuffer) {
            try {
                DatagramPacket p = new DatagramPacket(tempBuffer, 1024, InetAddress.getByName(ipa), uitport);
                rs.send(p);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    public class Read extends Thread {

        public boolean read(byte[] tempBuffer) {
            try {
                DatagramPacket p = new DatagramPacket(tempBuffer, 1024);
                rs.receive(p);
                tempBuffer = p.getData();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return true;
        }
    }
}
